package com.cdty.chess.service.impl;

import com.cdty.chess.service.WebSocketEventHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class EventWebSocketHandler extends TextWebSocketHandler {
    private final Map<String, WebSocketEventHandler> eventHandlers;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public EventWebSocketHandler(List<WebSocketEventHandler> handlers) {
        this.eventHandlers = handlers.stream()
                .collect(Collectors.toMap(WebSocketEventHandler::getEventType, Function.identity()));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JsonNode rootNode = objectMapper.readTree(message.getPayload());
        String eventType = rootNode.get("event").asText();
        JsonNode data = rootNode.get("data");

        WebSocketEventHandler handler = eventHandlers.get(eventType);
        if (handler != null) {
            handler.handleEvent(session, data);
        } else {
            session.sendMessage(new TextMessage("未知事件类型：" + eventType));
        }
    }
}